package com.cheng.spider.util;

import org.apache.http.Header;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

public class RequestPrinter {

    private HttpRequestBase request;

    public RequestPrinter(HttpRequestBase request) {
        this.request = request;
    }

    public void printRequestLine() {
        System.out.println(request.getRequestLine());
    }

    public void printHeaders() {
        for (Header header : request.getAllHeaders()) {
            System.out.println(header.getName() + ": " + header.getValue());
        }
    }


    public void printRequest() {
        printRequestLine();
        printHeaders();
        System.out.println();
        printBody();
    }

    private void printBody() {
        if (request instanceof HttpPost) {
            try {
                InputStream in = null;
                in = ((HttpPost) request).getEntity().getContent();
                BufferedReader reader = new BufferedReader(new InputStreamReader(in));
                String s;
                while ((s = reader.readLine()) != null) {
                    System.out.println(s);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

}
